package org.yinweichen.llm_dataset_backend.service.impl;

import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.yinweichen.llm_dataset_backend.entity.QuestionTag;
import org.yinweichen.llm_dataset_backend.entity.QuestionTagId;
import org.yinweichen.llm_dataset_backend.entity.StandardQuestion;
import org.yinweichen.llm_dataset_backend.entity.StandardQuestionId;
import org.yinweichen.llm_dataset_backend.repository.QuestionTagRepository;
import org.yinweichen.llm_dataset_backend.repository.StandardQuestionRepository;
import org.yinweichen.llm_dataset_backend.service.QuestionTagService;
import java.util.List;

@Service
@RequiredArgsConstructor
public class QuestionTagServiceImpl implements QuestionTagService {
    private final QuestionTagRepository questionTagRepository;
    private final StandardQuestionRepository standardQuestionRepository;

    @Override
    public void addTag(Long questionId, String version, String tag) {
        StandardQuestion question = standardQuestionRepository.findById(new StandardQuestionId(questionId, version))
        .orElseThrow(() -> new IllegalArgumentException("Question not found"));
        if (questionTagRepository.existsById(new QuestionTagId(questionId, version, tag))) {
            throw new IllegalArgumentException("Tag already exists");
        }
        QuestionTag questionTag = QuestionTag.builder()
                .id(questionId)
                .question(question)
                .version(version)
                .tag(tag)
                .build();
        questionTagRepository.save(questionTag);
    }

    @Override
    @Transactional
    public void removeTag(Long questionId, String version, String tag) {
        questionTagRepository.deleteByIdAndVersionAndTag(questionId, version, tag);
    }

    @Override
    public List<String> getAllTags() {
        return questionTagRepository.findAllDistinctTags();
    }

    @Override
    public List<String> getTagsByQuestionIdAndVersion(Long questionId, String version) {
        return questionTagRepository.findTagsByQuestionIdAndVersion(questionId, version);
    }
}